﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace HeadCounter.Armourer.Requesters
{
    public class Itemiser : WebRequester
    {
        private readonly object _sync = new object();
        private readonly Queue<int> _itemQueue = new Queue<int>();

        public void EnqueueGetItem(int itemId)
        {
            lock (_sync)
            {
                if (!_itemQueue.Contains(itemId))
                {
                    _itemQueue.Enqueue(itemId);
                    //_itemQueue.Enqueue(48483);
                }
            }
        }

        public override ReqeusterDataType GetDataType()
        {
            return ReqeusterDataType.Item;
        }

        public override bool HasWork()
        {
            lock (_sync)
            {
                return _itemQueue.Count() > 0;
            }
        }

        public override XElement RequestData(BackgroundWorker worker)
        {
            int id;

            lock (_sync)
            {
                id = _itemQueue.Dequeue();
            }

            worker.ReportProgress(0, "Downloading item " + id);
            return GetItem(id);
        }

        private XElement GetItem(int id)
        {
            var uri = GetItemUri(id);
            var xmlText = GetWebData(uri);

            XElement data = null;
            if (!string.IsNullOrEmpty(xmlText))
            {
                try
                {
                    data = XElement.Parse(xmlText).Element("itemTooltips").Element("itemTooltip");

                    var icon = data.Element("icon");
                    if (icon != null)
                    {
                        var iconFile = GetIconFileName(icon.Value);
                        if (!File.Exists(iconFile))
                        {
                            GetWebFile(GetIconAddress(icon.Value), iconFile);
                        }
                    }
                }
                catch (Exception e)
                {
                    // todo handle exception properly.
                    throw new SystemException("Error parsing xml for item " + id + " " + e.Message);
                }
            }

            return data;
        }

        private Uri GetItemUri(int id)
        {
            return new Uri(string.Format("http://www.wowarmory.com/item-tooltip.xml?i={0}", id));
        }

        private string GetIconAddress(string icon)
        {
            return string.Format("http://www.wowarmory.com//wow-icons//_images//64x64//{0}.jpg", icon);
        }

        private string GetIconFileName(string icon)
        {
            if (!Directory.Exists("icons"))
            {
                Directory.CreateDirectory("icons");
            }

            return "icons//" + icon + ".jpg";
        }
    }
}